home *** CD-ROM | disk | FTP | other *** search
/ Over 1,000 Windows 95 Programs / Over 1000 Windows 95 Programs (Microforum) (Disc 1).iso / 0957 / gnugrep / cl / grep.c < prev    next >
Encoding:
C/C++ Source or Header  |  1996-06-28  |  19.8 KB  |  845 lines

  1. /* grep.c - main driver file for grep.
  2.    Copyright (C) 1992 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 2, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  17.  
  18.    Written July 1992 by Mike Haertel.  */
  19.  
  20. #pragma warning(disable : 4018) //signed/unsigned mismatch
  21.  
  22. #define HAVE_WORKING_MMAP  // Undefine this to not use Win32 Memory Mapping
  23. #include <windows.h>
  24. #include <errno.h>
  25. #include <stdio.h>
  26. #include <errno.h>
  27. #include <stdlib.h>
  28. #include <string.h>
  29. #include <memory.h>
  30. #include <sys/stat.h>
  31. #include <sys/types.h>
  32. #include <fcntl.h>
  33. #include <io.h>
  34. #ifndef _WIN32
  35. //#include "getpagesize.h"
  36. #endif
  37. #include "grep.h"
  38. #include "getopt.h"
  39.  
  40. #undef MAX
  41. #define MAX(A,B) ((A) > (B) ? (A) : (B))
  42.  
  43. typedef char * caddr_t;
  44.  
  45. #define VOID void
  46.     
  47. /* Define flags declared in grep.h. */
  48. char *matcher;
  49. int match_icase;
  50. int match_words;
  51. int match_lines;
  52.  
  53. /* Functions we'll use to search. */
  54. static void (*compile)();
  55. static char *(*execute)();
  56.  
  57. /* For error messages. */
  58. static char *prog;
  59. static char *filename;
  60. static int errseen;
  61.  
  62.  
  63. #ifdef _WIN32
  64. HFILE hFile;
  65. OFSTRUCT ReOpenBuff;
  66. HANDLE hMapAddr;
  67. caddr_t pMappedAddress;
  68.  
  69. long getpagesize()
  70. //-----------------
  71. {    SYSTEM_INFO sysInfo;
  72.     GetSystemInfo(&sysInfo);
  73.     return sysInfo.dwPageSize;
  74. }
  75. #endif
  76.  
  77. /* Print a message and possibly an error string.  Remember
  78.    that something awful happened. */
  79. static void error(const char *mesg, int errnum)
  80. //---------------------------------------------
  81. {if (errnum)
  82.     fprintf(stderr, "%s: %s: %s\n", prog, mesg, strerror(errnum));
  83.   else
  84.     fprintf(stderr, "%s: %s\n", prog, mesg);
  85.   errseen = 1;
  86. }
  87.  
  88. /* Like error(), but die horribly after printing. */
  89. void fatal(const char *mesg, int errnum)
  90. //--------------------------------------
  91. { error(mesg, errnum);
  92.   exit(2);
  93. }
  94.  
  95. /* Interface to handle errors and fix library lossage. */
  96. char *xmalloc(size_t size)
  97. //------------------------
  98. { char *result;
  99.  
  100.   result = malloc(size);
  101.   if (size && !result)
  102.     fatal("memory exhausted", 0);
  103.   return result;
  104. }
  105.  
  106. /* Interface to handle errors and fix some library lossage. */
  107. char *xrealloc(char *ptr, size_t size)
  108. //------------------------------------
  109. { char *result;
  110.  
  111.   if (ptr)
  112.     result = realloc(ptr, size);
  113.   else
  114.     result = malloc(size);
  115.   if (size && !result)
  116.     fatal("memory exhausted", 0);
  117.   return result;
  118. }
  119.  
  120. #define valloc malloc
  121.  
  122. /* Hairy buffering mechanism for grep.  The intent is to keep
  123.    all reads aligned on a page boundary and multiples of the
  124.    page size. */
  125.  
  126. static char *buffer;        /* Base of buffer. */
  127. static size_t bufsalloc;    /* Allocated size of buffer save region. */
  128. static size_t bufalloc;        /* Total buffer size. */
  129. static int bufdesc;        /* File descriptor. */
  130. static char *bufbeg;        /* Beginning of user-visible stuff. */
  131. static char *buflim;        /* Limit of user-visible stuff. */
  132.  
  133. #if defined(HAVE_WORKING_MMAP) 
  134. static int bufmapped;        /* True for ordinary files. */
  135. static struct stat bufstat;    /* From fstat(). */
  136. static off_t bufoffset;        /* What read() normally remembers. */
  137. #endif
  138.  
  139. /* Reset the buffer for a new file.  Initialize
  140.    on the first time through. */
  141. void reset(int fd)
  142. //----------------
  143. { static int initialized;
  144.  
  145.   if (!initialized)
  146.     {
  147.       initialized = 1;
  148. #ifndef BUFSALLOC
  149.       bufsalloc = MAX(8192, getpagesize());
  150. #else
  151.       bufsalloc = BUFSALLOC;
  152. #endif
  153.       bufalloc = 5 * bufsalloc;
  154.       /* The 1 byte of overflow is a kludge for dfaexec(), which
  155.      inserts a sentinel newline at the end of the buffer
  156.      being searched.  There's gotta be a better way... */
  157.       buffer = valloc(bufalloc + 1);
  158.       if (!buffer)
  159.     fatal("memory exhausted", 0);
  160.       bufbeg = buffer;
  161.       buflim = buffer;
  162.     }
  163.   bufdesc = fd; 
  164. #if defined(HAVE_WORKING_MMAP)
  165. #ifdef _WIN32
  166. #define S_ISREG(mode)  ((mode&0XF000) == 0X8000)
  167. #endif
  168.   if ( (fstat(fd, &bufstat) < 0) || (!S_ISREG(bufstat.st_mode)) )
  169.     bufmapped = 0;
  170.   else
  171.     { bufmapped = 1;
  172.       bufoffset = lseek(fd, 0, 1);
  173.     }
  174. #ifdef _WIN32
  175. if (pMappedAddress != NULL)
  176.     {    UnmapViewOfFile(pMappedAddress);
  177.         pMappedAddress = NULL;
  178.     }
  179. if (hMapAddr != NULL)
  180.     {    CloseHandle(hMapAddr);
  181.         hMapAddr = NULL;
  182.     }
  183. hMapAddr = CreateFileMapping((HANDLE)hFile, NULL, PAGE_READONLY,0,0,NULL);
  184. if (hMapAddr != NULL)
  185.     pMappedAddress = (caddr_t)MapViewOfFile(hMapAddr,FILE_MAP_READ,0,0,0);
  186. else
  187.     printf("Error %d opening file %s for mapping\n",GetLastError(),filename);
  188. #endif
  189. #endif
  190. }
  191.  
  192. /* Read new stuff into the buffer, saving the specified
  193.    amount of old stuff.  When we're done, 'bufbeg' points
  194.    to the beginning of the buffer contents, and 'buflim'
  195.    points just after the end.  Return count of new stuff. */
  196. static int fillbuf(size_t save)
  197. //-----------------------------
  198. { char *nbuffer, *dp, *sp;
  199.   int cc;
  200. #if defined(HAVE_WORKING_MMAP)
  201.   caddr_t maddr;
  202. #ifdef _WIN32
  203.     size_t sizeCopy;
  204. #endif
  205. #endif
  206.   static int pagesize;
  207.  
  208.   if (pagesize == 0 && (pagesize = getpagesize()) == 0)
  209.     abort();
  210.  
  211.   if (save > bufsalloc)
  212.     {    while (save > bufsalloc)
  213.                 bufsalloc *= 2;
  214.       bufalloc = 5 * bufsalloc;
  215.       nbuffer = valloc(bufalloc + 1);
  216.       if (!nbuffer)
  217.     fatal("memory exhausted", 0);
  218.     }
  219.   else
  220.     nbuffer = buffer;
  221.  
  222.   sp = buflim - save;
  223.   dp = nbuffer + bufsalloc - save;
  224.   bufbeg = dp;
  225.   while (save--)
  226.     *dp++ = *sp++;
  227.  
  228.   /* We may have allocated a new, larger buffer.  Since
  229.      there is no portable vfree(), we just have to forget
  230.      about the old one.  Sorry. */
  231.   buffer = nbuffer;
  232.  
  233. #if defined(HAVE_WORKING_MMAP)
  234.     #ifdef _WIN32
  235.     if (hMapAddr != NULL && pMappedAddress != NULL)
  236.         {    sizeCopy = bufalloc - bufsalloc;
  237.             if ( ((long)(bufoffset + sizeCopy)) >= bufstat.st_size)
  238.                 sizeCopy = bufstat.st_size - bufoffset;
  239.             memcpy(buffer + bufsalloc,pMappedAddress + bufoffset, sizeCopy);
  240.             cc = sizeCopy;
  241.       bufoffset += cc;
  242.         }
  243.     //else will do tryread below
  244.     #else
  245.   if (bufmapped && bufoffset % pagesize == 0
  246.       && bufstat.st_size - bufoffset >= bufalloc - bufsalloc)
  247.     {
  248.       maddr = buffer + bufsalloc;
  249.       maddr = mmap(maddr, bufalloc - bufsalloc, PROT_READ | PROT_WRITE,
  250.            MAP_PRIVATE | MAP_FIXED, bufdesc, bufoffset);
  251.       if (maddr == (caddr_t) -1)
  252.                 {
  253.                     fprintf(stderr, "%s: warning: %s: %s\n", filename,
  254.                         strerror(errno));
  255.                     goto tryread;
  256.                 }
  257.             
  258. #if 0
  259.       /* You might thing this (or MADV_WILLNEED) would help,
  260.      but it doesn't, at least not on a Sun running 4.1.
  261.      In fact, it actually slows us down about 30%! */
  262.       madvise(maddr, bufalloc - bufsalloc, MADV_SEQUENTIAL);
  263. #endif
  264.       cc = bufalloc - bufsalloc;
  265.       bufoffset += cc;
  266.     }
  267. #endif // _WIN32
  268.   else
  269.     {
  270.     tryread:
  271.       /* We come here when we're not going to use mmap() any more.
  272.      Note that we need to synchronize the file offset the
  273.      first time through. */
  274.       if (bufmapped)
  275.     {
  276.       bufmapped = 0;
  277.       lseek(bufdesc, bufoffset, 0);
  278.     }
  279.       cc = read(bufdesc, buffer + bufsalloc, bufalloc - bufsalloc);
  280.     }
  281. #else
  282.   cc = read(bufdesc, buffer + bufsalloc, bufalloc - bufsalloc);
  283. #endif
  284.   if (cc > 0)
  285.     buflim = buffer + bufsalloc + cc;
  286.   else
  287.     buflim = buffer + bufsalloc;
  288.   return cc;
  289. }
  290.  
  291. /* Flags controlling the style of output. */
  292. static int out_quiet;        /* Suppress all normal output. */
  293. static int out_invert;        /* Print nonmatching stuff. */
  294. static int out_file;        /* Print filenames. */
  295. static int out_line;        /* Print line numbers. */
  296. static int out_byte;        /* Print byte offsets. */
  297. static int out_before;        /* Lines of leading context. */
  298. static int out_after;        /* Lines of trailing context. */
  299.  
  300. /* Internal variables to keep track of byte count, context, etc. */
  301. static size_t totalcc;        /* Total character count before bufbeg. */
  302. static char *lastnl;        /* Pointer after last newline counted. */
  303. static char *lastout;        /* Pointer after last character output;
  304.                    NULL if no character has been output
  305.                    or if it's conceptually before bufbeg. */
  306. static size_t totalnl;        /* Total newline count before lastnl. */
  307. static int pending;        /* Pending lines of output. */
  308.  
  309. static void nlscan(char *lim)
  310. //---------------------------
  311. { char *beg;
  312.  
  313.   for (beg = lastnl; beg < lim; ++beg)
  314.     if (*beg == '\n')
  315.       ++totalnl;
  316.   lastnl = beg;
  317. }
  318.  
  319. static void prline(char *beg, char *lim, char sep)
  320. //------------------------------------------------
  321. { if (out_file)
  322.     printf("%s%c", filename, sep);
  323.   if (out_line)
  324.     {
  325.       nlscan(beg);
  326.       printf("%d%c", ++totalnl, sep);
  327.       lastnl = lim;
  328.     }
  329.   if (out_byte)
  330.     printf("%lu%c", totalcc + (beg - bufbeg), sep);
  331.   fwrite(beg, 1, lim - beg, stdout);
  332.   if (ferror(stdout))
  333.     error("writing output", errno);
  334.   lastout = lim;
  335. }
  336.  
  337. /* Print pending lines of trailing context prior to LIM. */
  338. static void prpending(char *lim)
  339. //------------------------------
  340. {
  341.   char *nl;
  342.  
  343.   if (!lastout)
  344.     lastout = bufbeg;
  345.   while (pending > 0 && lastout < lim)
  346.     {
  347.       --pending;
  348.       if ((nl = memchr(lastout, '\n', lim - lastout)) != 0)
  349.     ++nl;
  350.       else
  351.     nl = lim;
  352.       prline(lastout, nl, '-');
  353.     }
  354. }
  355.  
  356. /* Print the lines between BEG and LIM.  Deal with context crap.
  357.    If NLINESP is non-null, store a count of lines between BEG and LIM. */
  358. static void prtext(char *beg, char *lim, int *nlinesp)
  359. //---------------------------------------------------
  360. {
  361.   static int used;        /* avoid printing "--" before any output */
  362.   char *bp, *p, *nl;
  363.   int i, n;
  364.  
  365.   if (!out_quiet && pending > 0)
  366.     prpending(beg);
  367.  
  368.   p = beg;
  369.  
  370.   if (!out_quiet)
  371.     {
  372.       /* Deal with leading context crap. */
  373.  
  374.       bp = lastout ? lastout : bufbeg;
  375.       for (i = 0; i < out_before; ++i)
  376.     if (p > bp)
  377.       do
  378.         --p;
  379.       while (p > bp && p[-1] != '\n');
  380.  
  381.       /* We only print the "--" separator if our output is
  382.      discontiguous from the last output in the file. */
  383.       if ((out_before || out_after) && used && p != lastout)
  384.     puts("--");
  385.  
  386.       while (p < beg)
  387.     {
  388.       nl = memchr(p, '\n', beg - p);
  389.       prline(p, nl + 1, '-');
  390.       p = nl + 1;
  391.     }
  392.     }
  393.  
  394.   if (nlinesp)
  395.     {
  396.       /* Caller wants a line count. */
  397.       for (n = 0; p < lim; ++n)
  398.     {
  399.       if ((nl = memchr(p, '\n', lim - p)) != 0)
  400.         ++nl;
  401.       else
  402.         nl = lim;
  403.       if (!out_quiet)
  404.         prline(p, nl, ':');
  405.       p = nl;
  406.     }
  407.       *nlinesp = n;
  408.     }
  409.   else
  410.     if (!out_quiet)
  411.       prline(beg, lim, ':');
  412.  
  413.   pending = out_after;
  414.   used = 1;
  415. }
  416.  
  417. /* Scan the specified portion of the buffer, matching lines (or
  418.    between matching lines if OUT_INVERT is true).  Return a count of
  419.    lines printed. */
  420. static int grepbuf(char *beg, char *lim)
  421. //--------------------------------------
  422. { int nlines, n;
  423.   register char *p, *b;
  424.   char *endp;
  425.  
  426.   nlines = 0;
  427.   p = beg;
  428.   while ((b = (*execute)(p, lim - p, &endp)) != 0)
  429.     {
  430.       /* Avoid matching the empty line at the end of the buffer. */
  431.       if (b == lim && ((b > beg && b[-1] == '\n') || b == beg))
  432.     break;
  433.       if (!out_invert)
  434.     {
  435.       prtext(b, endp, (int *) 0);
  436.       nlines += 1;
  437.     }
  438.       else if (p < b)
  439.     {
  440.       prtext(p, b, &n);
  441.       nlines += n;
  442.     }
  443.       p = endp;
  444.     }
  445.   if (out_invert && p < lim)
  446.     {
  447.       prtext(p, lim, &n);
  448.       nlines += n;
  449.     }
  450.   return nlines;
  451. }
  452.  
  453. /* Search a given file.  Return a count of lines printed. */
  454. static int grep(int fd)
  455. //---------------------
  456. { int nlines, i;
  457.   size_t residue, save;
  458.   char *beg, *lim;
  459.  
  460.   reset(fd);
  461.  
  462.   totalcc = 0;
  463.   lastout = 0;
  464.   totalnl = 0;
  465.   pending = 0;
  466.  
  467.   nlines = 0;
  468.   residue = 0;
  469.   save = 0;
  470.  
  471.   for (;;)
  472.     {
  473.       if (fillbuf(save) < 0)
  474.     {
  475.       error(filename, errno);
  476.       return nlines;
  477.     }
  478.       lastnl = bufbeg;
  479.       if (lastout)
  480.     lastout = bufbeg;
  481.       if (buflim - bufbeg == save)
  482.     break;
  483.       beg = bufbeg + save - residue;
  484.       for (lim = buflim; lim > beg && lim[-1] != '\n'; --lim)
  485.     ;
  486.       residue = buflim - lim;
  487.       if (beg < lim)
  488.     {
  489.       nlines += grepbuf(beg, lim);
  490.       if (pending)
  491.         prpending(lim);
  492.     }
  493.       i = 0;
  494.       beg = lim;
  495.       while (i < out_before && beg > bufbeg && beg != lastout)
  496.     {
  497.       ++i;
  498.       do
  499.         --beg;
  500.       while (beg > bufbeg && beg[-1] != '\n');
  501.     }
  502.       if (beg != lastout)
  503.     lastout = 0;
  504.       save = residue + lim - beg;
  505.       totalcc += buflim - bufbeg - save;
  506.       if (out_line)
  507.     nlscan(beg);
  508.     }
  509.   if (residue)
  510.     {
  511.       nlines += grepbuf(bufbeg + save - residue, buflim);
  512.       if (pending)
  513.     prpending(buflim);
  514.     }
  515.   return nlines;
  516. }
  517.  
  518. static char version[] = "GNU grep version 2.0";
  519.  
  520. #define USAGE \
  521.   "usage: %s [-[[AB] ]<num>] [-[CEFGVchilnqsvwx]] [-[ef]] <expr> [<files...>]\n"
  522.  
  523. static void usage()
  524. //-----------------
  525. {
  526.   fprintf(stderr, USAGE, prog);
  527.   exit(2);
  528. }
  529.  
  530. /* Go through the matchers vector and look for the specified matcher.
  531.    If we find it, install it in compile and execute, and return 1.  */
  532. int
  533. setmatcher(name)
  534.      char *name;
  535. {
  536.   int i;
  537.  
  538.   for (i = 0; matchers[i].name; ++i)
  539.     if (strcmp(name, matchers[i].name) == 0)
  540.       {
  541.     compile = matchers[i].compile;
  542.     execute = matchers[i].execute;
  543.     return 1;
  544.       }
  545.   return 0;
  546. }  
  547.  
  548. int main(int argc, char *argv[])
  549. //------------------------------
  550. {
  551.   char *keys;
  552.   size_t keycc, oldcc, keyalloc;
  553.   int keyfound, count_matches, no_filenames, list_files, suppress_errors;
  554.   int opt, cc, desc, count, status;
  555.   FILE *fp;
  556.   extern char *optarg;
  557.   extern int optind;
  558.  
  559. #ifdef _WIN32
  560.     HANDLE hFindFiles;
  561.     int bWildCard;
  562.     pMappedAddress = NULL;
  563.     hMapAddr = NULL;
  564.     hFile = 0;
  565. #endif
  566.  
  567.   prog = argv[0];
  568.   if (prog && strrchr(prog, '/'))
  569.     prog = strrchr(prog, '/') + 1;
  570.  
  571.   keys = NULL;
  572.   keycc = 0;
  573.   keyfound = 0;
  574.   count_matches = 0;
  575.   no_filenames = 0;
  576.   list_files = 0;
  577.   suppress_errors = 0;
  578.   matcher = NULL;
  579.  
  580.   while ((opt = getopt(argc, argv, "0123456789A:B:CEFGVX:bce:f:hiLlnqsvwxy"))
  581.      != EOF)
  582.     switch (opt)
  583.       {
  584.       case '0':
  585.       case '1':
  586.       case '2':
  587.       case '3':
  588.       case '4':
  589.       case '5':
  590.       case '6':
  591.       case '7':
  592.       case '8':
  593.       case '9':
  594.     out_before = 10 * out_before + opt - '0';
  595.     out_after = 10 * out_after + opt - '0';
  596.     break;
  597.       case 'A':
  598.     out_after = atoi(optarg);
  599.     if (out_after < 0)
  600.       usage();
  601.     break;
  602.       case 'B':
  603.     out_before = atoi(optarg);
  604.     if (out_before < 0)
  605.       usage();
  606.     break;
  607.       case 'C':
  608.     out_before = out_after = 2;
  609.     break;
  610.       case 'E':
  611.     if (matcher && strcmp(matcher, "egrep") != 0)
  612.       fatal("you may specify only one of -E, -F, or -G", 0);
  613.     matcher = "posix-egrep";
  614.     break;
  615.       case 'F':
  616.     if (matcher && strcmp(matcher, "fgrep") != 0)
  617.       fatal("you may specify only one of -E, -F, or -G", 0);;
  618.     matcher = "fgrep";
  619.     break;
  620.       case 'G':
  621.     if (matcher && strcmp(matcher, "grep") != 0)
  622.       fatal("you may specify only one of -E, -F, or -G", 0);
  623.     matcher = "grep";
  624.     break;
  625.       case 'V':
  626.     fprintf(stderr, "%s\n", version);
  627.     break;
  628.       case 'X':
  629.     if (matcher)
  630.       fatal("matcher already specified", 0);
  631.     matcher = optarg;
  632.     break;
  633.       case 'b':
  634.     out_byte = 1;
  635.     break;
  636.       case 'c':
  637.     out_quiet = 1;
  638.     count_matches = 1;
  639.     break;
  640.       case 'e':
  641.     cc = strlen(optarg);
  642.     keys = xrealloc(keys, keycc + cc + 1);
  643.     if (keyfound)
  644.       keys[keycc++] = '\n';
  645.     strcpy(&keys[keycc], optarg);
  646.     keycc += cc;
  647.     keyfound = 1;
  648.     break;
  649.       case 'f':
  650.     fp = strcmp(optarg, "-") != 0 ? fopen(optarg, "r") : stdin;
  651.     if (!fp)
  652.       fatal(optarg, errno);
  653.     for (keyalloc = 1; keyalloc <= keycc; keyalloc *= 2)
  654.       ;
  655.     keys = xrealloc(keys, keyalloc);
  656.     oldcc = keycc;
  657.     if (keyfound)
  658.       keys[keycc++] = '\n';
  659.     while (!feof(fp)
  660.            && (cc = fread(keys + keycc, 1, keyalloc - keycc, fp)) > 0)
  661.       {
  662.         keycc += cc;
  663.         if (keycc == keyalloc)
  664.           keys = xrealloc(keys, keyalloc *= 2);
  665.       }
  666.     if (fp != stdin)
  667.       fclose(fp);
  668.     /* Nuke the final newline to avoid matching a null string. */
  669.     if (keycc - oldcc > 0 && keys[keycc - 1] == '\n')
  670.       --keycc;
  671.     keyfound = 1;
  672.     break;
  673.       case 'h':
  674.     no_filenames = 1;
  675.     break;
  676.       case 'i':
  677.       case 'y':            /* For old-timers . . . */
  678.     match_icase = 1;
  679.     break;
  680.       case 'L':
  681.     /* Like -l, except list files that don't contain matches.
  682.        Inspired by the same option in Hume's gre. */
  683.     out_quiet = 1;
  684.     list_files = -1;
  685.     break;
  686.       case 'l':
  687.     out_quiet = 1;
  688.     list_files = 1;
  689.     break;
  690.       case 'n':
  691.     out_line = 1;
  692.     break;
  693.       case 'q':
  694.     out_quiet = 1;
  695.     break;
  696.       case 's':
  697.     suppress_errors = 1;
  698.     break;
  699.       case 'v':
  700.     out_invert = 1;
  701.     break;
  702.       case 'w':
  703.     match_words = 1;
  704.     break;
  705.       case 'x':
  706.     match_lines = 1;
  707.     break;
  708.       default:
  709.     usage();
  710.     break;
  711.       }
  712.  
  713.   if (!keyfound)
  714.     if (optind < argc)
  715.       {
  716.     keys = argv[optind++];
  717.     keycc = strlen(keys);
  718.       }
  719.     else
  720.       usage();
  721.  
  722.   if (!matcher)
  723.     matcher = prog;
  724.  
  725.   if (!setmatcher(matcher) && !setmatcher("default"))
  726.     abort();
  727.  
  728.   (*compile)(keys, keycc);
  729.  
  730.   if (argc - optind > 1 && !no_filenames)
  731.     out_file = 1;
  732.  
  733.   status = 1;
  734.  
  735. #ifdef _WIN32
  736.     bWildCard = FALSE;
  737. #endif
  738.   if (optind < argc)
  739.     while (optind < argc)
  740.       {    
  741.             #ifdef _WIN32
  742.             WIN32_FIND_DATA FindData;
  743.             if ( ( strchr(argv[optind],'*') != NULL) || (strchr(argv[optind],'?') != NULL) )
  744.                 {    if (! bWildCard)
  745.                         {    hFindFiles = FindFirstFile(argv[optind],&FindData);
  746.                             if (hFindFiles != INVALID_HANDLE_VALUE)
  747.                                 {    bWildCard = TRUE;
  748.                                     out_file = 1;
  749.                                 }
  750.                             else
  751.                                 bWildCard = FALSE;    
  752.                         }
  753.                 }
  754.             else
  755.                 bWildCard = FALSE;
  756.             if (hFile != 0)
  757.                 _lclose(hFile);
  758.             if (bWildCard)
  759.                 hFile = OpenFile(FindData.cFileName, &ReOpenBuff, OF_READ | OF_SHARE_DENY_NONE);
  760.             else
  761.                 hFile = strcmp(argv[optind], "-") ? OpenFile(argv[optind], &ReOpenBuff, OF_READ | OF_SHARE_DENY_NONE) : 0;
  762.             #endif
  763. #ifdef _WIN32
  764.                 if (bWildCard)
  765.                     desc = strcmp(FindData.cFileName, "-") ? open(FindData.cFileName, O_RDONLY) : 0;
  766.                 else
  767. #endif
  768.                 desc = strcmp(argv[optind], "-") ? open(argv[optind], O_RDONLY) : 0;
  769.             
  770.             if ( (desc < 0)
  771. #ifdef _WIN32
  772.                 || (hFile == -1)
  773. #endif
  774.                 )
  775.                 {
  776.                     if (!suppress_errors)
  777. #ifdef _WIN32
  778.                         if (bWildCard)
  779.                             error(FindData.cFileName, errno);
  780.                         else
  781. #endif
  782.                             error(argv[optind], errno);
  783.                 }
  784.             else
  785.                 {
  786.                     filename = desc == 0 ? "(standard input)" : argv[optind];
  787. #ifdef _WIN32
  788.                     if (bWildCard)
  789.                         filename = FindData.cFileName;
  790. #endif
  791.                     count = grep(desc);
  792.                     if (count_matches)
  793.                         {
  794.                 if (out_file)
  795.                     printf("%s:", filename);
  796.                 printf("%d\n", count);
  797.                         }
  798.                     if (count)
  799.                         {
  800.                 status = 0;
  801.                 if (list_files == 1)
  802.                     printf("%s\n", filename);
  803.                         }
  804.                     else if (list_files == -1)
  805.                         printf("%s\n", filename);
  806.                 }
  807.             if (desc != 0)
  808.                 close(desc);
  809. #ifdef _WIN32
  810.             if (bWildCard)
  811.                 {    if (! FindNextFile(hFindFiles, &FindData))
  812.                         {    bWildCard = FALSE;
  813.                             ++optind;
  814.                         }
  815.                 }
  816.             else
  817. #endif
  818.                 ++optind;
  819.       }
  820.   else
  821.     {
  822.       filename = "(standard input)";
  823.       count = grep(0);
  824.       if (count_matches)
  825.     printf("%d\n", count);
  826.       if (count)
  827.     {
  828.       status = 0;
  829.       if (list_files == 1)
  830.         printf("(standard input)\n");
  831.     }
  832.       else if (list_files == -1)
  833.     printf("(standard input)\n");
  834.     }
  835.     #ifdef _WIN32
  836.     if (hFile != 0)
  837.         _lclose(hFile);
  838.     if (pMappedAddress != NULL)
  839.         UnmapViewOfFile(pMappedAddress);
  840.     if (hMapAddr != NULL)
  841.         CloseHandle(hMapAddr);
  842.     #endif
  843.   return(errseen ? 2 : status);
  844. }
  845.